import json

from google.appengine.api.users import User, get_current_user

from simpleapi import Namespace

from apps.utils.sanitizers import sanitize_name
from apps.accounts.models import UserProfile

class AccountsNamespace(Namespace):
    """Account Management API. Anything the user can manage related directly
    to their account should be manage here."""
    __version__ = 1

    def update_user(self, name):
        user = get_current_user()
        up = UserProfile.gql("WHERE user = :1", user).get()
        up.name = sanatize_name(name)
        up.put()

        return json.dumps({'sucess': True})

    def add_ignore(self, user_email):
        user = get_current_user()
        to_ignore = User(user_email)
        up = UserProfile.gql("WHERE user = :1", user).get()
        ignored = bool(UserProfile.gql("WHERE user = :1 AND ignored = :2",
                                       user, to_ignore).count())

        if not ignored:
            up.ignored.append(to_ignore)

        return json.dumps({'sucess': True})

    def remove_ignore(self, user_email):
        user = get_current_user()
        remove_ignore = User(user_email)
        up = UserProfile.gql("WHERE user = :1", user).get()
        ignored = bool(UserProfile.gql("WHERE user = :1 AND ignored = :2",
                                       user, remove_ignore).count())

        if ignored:
            up.ignored.remove(remove_ignore)

        return json.dumps({'sucess': True})
